package com.css.zfzx.fxpg.modules.risk.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.risk.repository.FxRiskResultNativeRepository;
import com.css.zfzx.fxpg.modules.risk.repository.FxRiskResultRepository;
import com.css.zfzx.fxpg.modules.risk.repository.entity.FxRiskResultEntity;
import com.css.zfzx.fxpg.modules.risk.service.FxRiskResultService;
import com.css.zfzx.fxpg.modules.risk.viewobjects.FxRiskResultQueryParams;
import com.css.zfzx.fxpg.modules.risk.viewobjects.FxRiskResultVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.modules.vulnerability.area.repository.entity.FxVulnerabilityAreaEntity;
import com.css.zfzx.fxpg.modules.vulnerability.area.viewobjects.FxVulnerabilityAreaQueryParams;
import com.css.zfzx.fxpg.modules.vulnerability.area.viewobjects.FxVulnerabilityAreaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author leon
 * @date 2020-11-12
 */
@Service
@Slf4j
public class FxRiskResultServiceImpl implements FxRiskResultService {

    @Autowired
    private FxRiskResultRepository fxRiskResultRepository;
    @Autowired
    private FxRiskResultNativeRepository fxRiskResultNativeRepository;

    @Override
    public JSONObject queryFxRiskResults(FxRiskResultQueryParams queryParams, int curPage, int pageSize) {
        Page<FxRiskResultEntity> fxRiskResultPage = this.fxRiskResultNativeRepository.queryFxRiskResults(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxRiskResultPage);
        return jsonObject;
    }


    @Override
    public FxRiskResultEntity getFxRiskResult(String id) {
        FxRiskResultEntity fxRiskResult = this.fxRiskResultRepository.findById(id).orElse(null);
        return fxRiskResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxRiskResultEntity saveFxRiskResult(FxRiskResultEntity fxRiskResult) {
        String uuid = UUIDGenerator.getUUID();
        fxRiskResult.setId(uuid);
        fxRiskResult.setCreateUser(PlatformSessionUtils.getUserId());
        fxRiskResult.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxRiskResultRepository.save(fxRiskResult);
        return fxRiskResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxRiskResultEntity updateFxRiskResult(FxRiskResultEntity fxRiskResult) {
        fxRiskResult.setUpdateUser(PlatformSessionUtils.getUserId());
        fxRiskResult.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxRiskResult.getId();
        FxRiskResultEntity one = fxRiskResultRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxRiskResult, one);
        this.fxRiskResultRepository.save(one);
        return fxRiskResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxRiskResults(List<String> ids) {
        List<FxRiskResultEntity> fxRiskResultList = this.fxRiskResultRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxRiskResultList) && fxRiskResultList.size() > 0) {
            for (FxRiskResultEntity fxRiskResult : fxRiskResultList) {
                this.fxRiskResultRepository.delete(fxRiskResult);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            //
            params.setTitleRows(1);
            // 设置解析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxRiskResultVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxRiskResultVO.class, params);
            List<FxRiskResultVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxRiskResultVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxRiskResultVO riskResultVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + riskResultVO.getRowNum() + "行" + riskResultVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    private void saveExcel(List<FxRiskResultVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxRiskResultEntity riskResultEntity = new FxRiskResultEntity();
            FxRiskResultVO riskResultVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(riskResultVO, riskResultEntity);
            saveFxRiskResult(riskResultEntity);
        }
    }

    @Override
    public String exportExcel(FxRiskResultQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxRiskResultEntity> riskResults = fxRiskResultNativeRepository.listFxRiskResults(queryParams);
            // 深拷贝
            ArrayList<FxRiskResultVO> vos = new ArrayList<>();
            for (FxRiskResultEntity riskResultEntity : riskResults) {
                FxRiskResultVO vo = new FxRiskResultVO();
                BeanUtils.copyProperties(riskResultEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "风险结果数据统计", "风险结果数据统计", FxRiskResultVO.class, "风险结果数据.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

}
